<?php
$error = '/usr/bin/php /app/index.php local|product' . PHP_EOL;
if($argc < 2){
    exit($error);
}
if(!in_array($argv[1], ['local', 'product'])){
    exit($error);
}
define('PROJECT_PATH', dirname(__FILE__));
require_once(PROJECT_PATH . '/src/Php/init.php');

$http = new swoole_http_server('0.0.0.0', 80);
$http->set(['enable_static_handler' => true, 'document_root' => PUBLIC_PATH, 'package_max_length' => 10485760000]);
$http->on('start', function($server){
    echo 'start at:' . date('Y-m-d H:i:s') . PHP_EOL;
});

$http->on('request', function($request, $response){
    $server = $request->server;
    $list = parseUrl($server['request_uri']);
    if(strtoupper($server['request_method']) != 'HEAD' && $server['request_uri'] == '/'){
        $list = ['Index', 'Index', 'index'];
    }
    if(count($list) != 3){
        $response->end(URL_ERROR);
        return false;
    }
    $module = $list[0];
    $controller = $list[1];
    $action = $list[2] . 'Action';
    $class = "Application\\{$module}\\Controller\\{$controller}";
    if(!class_exists($class)){
        $response->end(CLASS_ERROR);
        return false;
    }
    $instance = new $class($request, $response);
    if($instance->hasJump){
        return false;
    }
    if(!method_exists($instance, $action)){
        $response->end(METHOD_ERROR);
        return false;
    }
    if(method_exists($instance, 'init')){
        $instance->init();
    }
    $list = get_class_methods($instance);
    foreach($list as $method){
        if(startWith($method, '_init')){
            $instance->{$method}();
        }
    }
    $instance->{$action}();
});

$http->start();